package com.stone.db.dbsecurity;

import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr;
import com.alibaba.druid.sql.ast.statement.SQLExprTableSource;
import com.alibaba.druid.sql.ast.statement.SQLSelect;
import com.alibaba.druid.sql.ast.statement.SQLSelectStatement;
import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlInsertStatement;
import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlSelectQueryBlock;
import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlUpdateStatement;

import java.util.List;

/**
 * Created by stone on 2017/11/29.
 */
public final class SQLParse {

	private String dbType;

	public SQLParse(String dbType) {
		this.dbType = dbType;
	}

	/**
	 *
	 * @param sql
	 * @return
	 */
	public SQLParseResult parseSQL(String sql) {

		SQLParseResult sqlParseResult = new SQLParseResult();

		final List<SQLStatement> sqlStatements = SQLUtils.parseStatements(sql, this.dbType);

		final SQLStatement sqlStatement = sqlStatements.get(0);

		if (sqlStatement instanceof MySqlUpdateStatement) {
			MySqlUpdateStatement updateStatement = (MySqlUpdateStatement) sqlStatement;
			sqlParseResult.setTableName(updateStatement.getTableName().toString());
		}
		else if (sqlStatement instanceof MySqlInsertStatement) {
			MySqlInsertStatement insertStatement = (MySqlInsertStatement) sqlStatement;
			sqlParseResult.setTableName(insertStatement.getTableName().toString());
		}else if(sqlStatement instanceof SQLSelectStatement){
			SQLSelectStatement sqlSelectStatement = (SQLSelectStatement) sqlStatement;
			final SQLSelect select = sqlSelectStatement.getSelect();
			final MySqlSelectQueryBlock query = (MySqlSelectQueryBlock)select.getQuery();
			final SQLExprTableSource sqlExprTableSource = (SQLExprTableSource) query.getFrom();
			final SQLIdentifierExpr expr = (SQLIdentifierExpr) sqlExprTableSource.getExpr();
			sqlParseResult.setTableName(expr.getName());
		}
		return sqlParseResult;
	}
}
